<template>
  <a-card :bordered="false">
    <a-tabs :active-key="activePackageId" tabPosition="top" @change="handleChangeActivePackageId">
      <a-tab-pane v-for="item in packageList" :key="item.dataId">
        <template slot="tab">
          {{ item.packageName }}
          <a-icon type="edit" style="margin-left: 10px" @click.stop="handleEditPackage(item)" />
          <a-popconfirm title="确定删除吗?" @confirm.stop="() => handleDeletePackage(item.dataId)">
            <a-icon type="delete" />
          </a-popconfirm>
        </template>
        <a-table
          rowKey="dataId"
          :loading="dataLoading"
          :columns="columns"
          :data-source="packageServiceList"
          :row-selection="rowSelection"
          :pagination="false"
        >
          <template slot="serviceName" slot-scope="text, record">
            {{record.serviceName}}
            <!-- <editable :text="text" :id="record.dataId" @serviceNameChange="serviceNameChange"/> -->
          </template>
          <template slot="serviceMonth" slot-scope="text, record">
            <!-- <a-select style="width: 100px" v-model="record.serviceMonth"  placeholder="请选择服务周期" :getPopupContainer= "(target) => target.parentNode">
              <a-select-option :value="item.value" v-for="item in periodList" :key="item.value">{{ item.label }}</a-select-option>
            </a-select> -->
            <!-- <j-multi-select-tag
              style="width: 100px"
              v-model="record.serviceMonth"
              :options="periodList"
              placeholder="请选择服务周期">
            </j-multi-select-tag> -->
            <span @click="modifyServiceMonth(record)" v-if="record.serviceMonth">{{ record.serviceMonthText }}</span>
            <span @click="modifyServiceMonth(record)" v-else>暂未设置</span>
          </template>
          <template slot="serviceCount" slot-scope="text, record">
            <a-input style="width: 100px" v-model="record.serviceCount" />
          </template>
          <span slot="action" slot-scope="text, record">
            <a @click="handleEditPackageService(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteService(record.dataId)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="addBtn">
        <template slot="tab">
          <a-icon type="plus" @click="handleAddPackage" />
        </template>
      </a-tab-pane>
      <template slot="tabBarExtraContent">
        <a-button type="danger" @click="handleAddPackageService">
          新增服务
        </a-button>
        <a-button style="margin-left: 10px" type="danger" @click="handleEditCategory">
          服务分类
        </a-button>
      </template>
    </a-tabs>

    <a-row>
      <a-col :span="12" :offset="10" :style="{ marginTop: '20px' }">
        <a-button size="large" type="danger" @click="savePackageService" :loading="saveLoading">保存</a-button>
      </a-col>
    </a-row>

    <package-modal ref="packageModalForm" @ok="packageModalFormOk"></package-modal>
    <service-modal ref="serviceModalForm" @ok="serviceModalFormOk"></service-modal>
    <category-modal ref="categoryModalForm"></category-modal>
    <service-month-modal ref="serviceMonthModalForm" @ok="serviceMonthModalFormOk"></service-month-modal>
  </a-card>
</template>

<script>
import { PAGE_MENU_TYPE } from '@/store/mutation-types'
import { getAction, postAction, deleteAction } from '@/api/manage'
import Editable from './components/Editable'
import PackageModal from './modules/PackageModal'
import ServiceModal from './modules/ServiceModal'
import CategoryModal from './modules/CategoryModal'
import ServiceMonthModal from './modules/ServiceMonthModal'
import { numberToChinese } from '@/utils/util'
import moment from 'moment'
import { mapGetters } from 'vuex'
import { connectors } from '@antv/data-set'

export default {
  name: 'PackageTemplate',
  components: { PackageModal, ServiceModal, CategoryModal, ServiceMonthModal, Editable },
  data() {
    return {
      periodList: [],
      weekList: [
        {
          value: 1,
          label: '第一周'
        },
        {
          value: 2,
          label: '第二周'
        },
        {
          value: 3,
          label: '第三周'
        },
        {
          value: 4,
          label: '第四周'
        }
      ],
      monthList: [
        {
          value: 1,
          label: '第一个月'
        },
        {
          value: 2,
          label: '第二个月'
        },
        {
          value: 3,
          label: '第三个月'
        },
        {
          value: 4,
          label: '第四个月'
        },
        {
          value: 5,
          label: '第五个月'
        },
        {
          value: 6,
          label: '第六个月'
        },
        {
          value: 7,
          label: '第七个月'
        },
        {
          value: 8,
          label: '第八个月'
        },
        {
          value: 9,
          label: '第九个月'
        },
        {
          value: 10,
          label: '第十个月'
        },
        {
          value: 11,
          label: '第十一个月'
        },
        {
          value: 12,
          label: '第十二个月'
        }
      ],
      saveLoading: false,
      dataLoading: true,
      activePackageId: 0,
      packageList: [],
      columns: [
        // {
        //   title: '编号',
        //   dataIndex: 'dataId',
        //   key: 'dataId',
        //   scopedSlots: { customRender: 'dataId' },
        // },
        {
          title: '服务分类',
          dataIndex: 'serviceCategoryName',
          key: 'serviceCategoryName',
          scopedSlots: { customRender: 'serviceCategoryName' }
        },
        {
          title: '服务名称',
          dataIndex: 'serviceName',
          key: 'serviceName',
          scopedSlots: { customRender: 'serviceName' }
        },
        {
          title: '品牌/设备',
          dataIndex: 'serviceBrand',
          key: 'serviceBrand',
          scopedSlots: { customRender: 'serviceBrand' }
        },
        //      {
        //        title: '单项零售价',
        //        dataIndex: 'servicePrice',
        //        key: 'servicePrice',
        //        scopedSlots: { customRender: 'servicePrice' },
        //      },
        //      {
        //        title: '折扣价',
        //        dataIndex: 'serviceDiscount',
        //        key: 'serviceDiscount',
        //        scopedSlots: { customRender: 'serviceDiscount' },
        //      },
        {
          title: '服务周期',
          dataIndex: 'serviceMonth',
          key: 'serviceMonth',
          scopedSlots: { customRender: 'serviceMonth' }
        },
        {
          title: '服务次数',
          dataIndex: 'serviceCount',
          key: 'serviceCount',
          scopedSlots: { customRender: 'serviceCount' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: 170
        }
      ],
      selectedRowKeys: [],
      selectedRows: [],
      packageServiceList: [],
      packageType: null,
      packagePeriod: null
    }
  },
  watch: {
    activePackageId() {
      this.selectedRowKeys = []
      this.selectedRows = []
      if (this.activePackageId > 0) {
        console.log('activePackageId', this.activePackageId)
        this.handleGetPackageServiceList()
      }
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        },
        onSelect: (record, selected, selectedRows) => {
          record.flag = selected
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
          selectedRows.forEach((item, index) => {
            item.flag = selected
          })
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
          console.log('selectall', this.selectedRowKeys, selectedRows)
        }
      }
    }
  },
  created() {
    this.getInit()
  },
  methods: {
    ...mapGetters(['doctorId', 'orgCode']),
    async getInit() {
      await this.handleGetPackageList()
      await this.handleGetPackageServiceList()
    },
    handleGetPackageList() {
      getAction('107/03/1070309', {doctorId: this.doctorId(), orgCode: this.orgCode()}).then(res => {
        if (res.success) {
          this.packageList = res.result
          this.activePackageId = this.packageList[0] && this.packageList[0].dataId
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleGetPackageServiceList() {
      this.dataLoading = true
      getAction('107/03/1070302', { packageId: this.activePackageId, doctorId: this.doctorId(), orgCode: this.orgCode() })
        .then(res => {
          if (res.success) {
            this.packageServiceList = res.result.serviceList
            this.packageType = res.result.packageType
            this.packagePeriod = res.result.packagePeriod
            // this.periodList = res.result.packageType == 1 ? this.monthList : this.weekList
            // console.log('this.periodList', this.periodList);
            if (this.packageServiceList.length > 0) {
              this.selectedRowKeys = []
              this.selectedRows = []
              this.packageServiceList.forEach(item => {
                this.$set(item, 'serviceMonthText', numberToChinese(item.serviceMonth, this.packageType))
                if (item.flag === true) {
                  this.selectedRowKeys.push(item.dataId)
                  this.selectedRows.push(item)
                }
              })
            }
            console.log(this.packageServiceList)
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.dataLoading = false
        })
    },
    handleChangeActivePackageId(key) {
      if (key === 'addBtn') {
        return false
      } else {
        this.activePackageId = key
      }
    },
    handleAddPackage() {
      this.$refs.packageModalForm.add()
      this.$refs.packageModalForm.title = '新增服务包'
      this.$refs.packageModalForm.disableSubmit = false
    },
    handleEditPackage(record) {
      this.$refs.packageModalForm.edit(record)
      this.$refs.packageModalForm.title = '编辑服务包'
      this.$refs.packageModalForm.disableSubmit = false
    },
    handleDeletePackage(id) {
      deleteAction('107/03/1070312', { packageId: id, doctorId: this.doctorId(), orgCode: this.orgCode() }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.handleGetPackageList()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    packageModalFormOk() {
      this.getInit()
    },
    serviceModalFormOk() {
      this.getInit()
    },
    handleAddPackageService() {
      this.$refs.serviceModalForm.add()
      this.$refs.serviceModalForm.title = '新增服务'
      this.$refs.serviceModalForm.disableSubmit = false
    },
    handleEditPackageService(record) {
      this.$refs.serviceModalForm.edit(record)
      this.$refs.serviceModalForm.title = '编辑服务'
      this.$refs.serviceModalForm.disableSubmit = false
    },
    handleDeleteService(id) {
      deleteAction('107/03/1070305', { serviceId: id, doctorId: this.doctorId(), orgCode: this.orgCode() }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.handleGetPackageServiceList()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleEditCategory() {
      this.$refs.categoryModalForm.edit()
      this.$refs.categoryModalForm.title = '服务分类'
      this.$refs.categoryModalForm.disableSubmit = false
    },
    modifyServiceMonth(data) {
      const record = JSON.parse(JSON.stringify(data))
      record.packageType = this.packageType
      record.packagePeriod = this.packagePeriod
      record.serviceMonth = record.serviceMonth != null ? record.serviceMonth.toString().split(',') : []
      console.log(record)
      this.$refs.serviceMonthModalForm.edit(record)
      this.$refs.serviceMonthModalForm.title = '设置 ' + record.serviceName + ' 服务周期'
    },
    serviceMonthModalFormOk(data) {
      console.log(data.dataId)
      const index = this.packageServiceList.findIndex(item => {
        return item.dataId == data.dataId
      })
      const serviceMonth = data.serviceMonth.length > 0 ? data.serviceMonth.join(',') : null
      this.$set(this.packageServiceList[index], 'serviceMonth', serviceMonth)
      this.$set(this.packageServiceList[index], 'serviceMonthText', numberToChinese(serviceMonth, data.packageType))
      console.log('dddddddddddddddd', this.packageServiceList[index])
    },
    savePackageService() {
      this.saveLoading = true
      console.log(this.packageServiceList)
      const model = {
        services: this.selectedRows,
        packageId: this.activePackageId,
        doctorId: this.doctorId(),
        orgCode: this.orgCode()
      }
      console.log(model)
      postAction('107/03/1070311', model)
        .then(res => {
          if (res.success) {
            this.$message.success('保存成功')
            this.handleGetPackageServiceList()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(_ => {
          this.saveLoading = false
        })
    },
    serviceNameChange(data) {
      if(data.id !=null && data.value != null) {
        // postAction('107/03/1070311', model)
        // .then(res => {
        //   if (res.success) {
        //     this.$message.success('保存成功')
        //     this.handleGetPackageServiceList()
        //   } else {
        //     this.$message.warning(res.message)
        //   }
        // })
        // .finally(_ => {
        //   this.saveLoading = false
        // })
      }
    }
  }
}
</script>

<style lang="less" scoped></style>

